<template>
  <div class="biz-container">
    <table-layout
      :haveSider="false"
      :isStandTable="false"
    >
      <template #headCustom>
        <a-button
          type="primary"
          @click="onBack"
        >返回</a-button>
      </template>
      <template #form>

        <div class="card">
          <div class="viewTitle">
            {{btn[0].name}}
            <a-button
              type="link"
              class="upAndDown"
              @click="upAndDown($event,0)"
            >
              <a-icon
                v-if="btn[0].isUp"
                type="up"
              />
              <a-icon
                v-else
                type="down"
              />
            </a-button>
            <span style="float:right;margin:0 10px">
              <a-button
                type="link"
                class="upAndDown"
                v-if="viewEdit"
                @click="onEdit(false)"
              >
                <a-icon type="edit" />
                编辑
              </a-button>
              <a-button
                type="link"
                class="upAndDown"
                v-else
                @click="onEdit(true)"
              >
                <a-icon type="edit" />
                取消编辑
              </a-button>
            </span>
          </div>
          <edit-delivery-order
            style="marginTop:30px"
            v-show="btn[0].isUp"
            ref="deliveryOrder"
            :formDatas="deliveryOrder"
            @onSave="onSave"
          ></edit-delivery-order>
          <!-- <a-list-info v-if="btn[0].isUp" span="12" :infoDatas="infoDatas" /> -->
        </div>
        <div class="dis"></div>
        <div class="card">
          <div class="viewTitle">
            {{btn[1].name}}
            <a-button
              type="link"
              class="upAndDown"
              @click="upAndDown($event,1)"
            >
              <a-icon
                v-if="btn[1].isUp"
                type="up"
              />
              <a-icon
                v-else
                type="down"
              />
            </a-button>
          </div>
          <a-list-table
            v-show="btn[1].isUp"
            tableId="goodsTable1"
            :columns="columns"
            :tableData="listdata"
            :haveChild="true"
            :pagination="pagination"
            :isSelecttion="false"
            :loading="loading"
            :scroll="{y:false}"
            @onTableChange="handleTableChange"
            @onselectChange="onselectChange"
            @onAction="onAction"
            @expand="onExpand"
            :links="links"
            :autoComputed="autoComputed"
            @onTouchlinkCell="onTouchlinkCell"
            :innerTable="innerTable"
            @onInnerAction="onInnerAction"
            @onInnerBlur="onInnerBlur"
          >
          </a-list-table>
        </div>
        <div class="dis"></div>
        <div class="card">
          <div class="viewTitle">
            {{btn[2].name}}
            <a-button
              type="link"
              class="upAndDown"
              @click="upAndDown($event,2)"
            >
              <a-icon
                v-if="btn[2].isUp"
                type="up"
              />
              <a-icon
                v-else
                type="down"
              />
            </a-button>
          </div>
          <a-button
            v-if="btn[2].isUp"
            @click="onAdd"
            type="primary"
            size="small"
          >新增发票</a-button>
          <a-list-table
            v-show="btn[2].isUp"
            tableId="invoicesTable"
            :columns="columns2"
            :tableData="listdata2"
            :pagination="pagination2"
            :isSelecttion="false"
            :loading="loading"
            :scroll="{y:false}"
            @onAction="onAction2"
          >
          </a-list-table>
        </div>

        <div style="textAlign:center;lineHeight:60px;height:60px">
          <!-- <a-button type="primary" @click="onCancel"  >取消</a-button>
            <a-button type="primary" @click="onSubmit" style="marginLeft:20px" >提交</a-button> -->
        </div>
      </template>
    </table-layout>
    <addModal
      ref="addModal"
      @onSubmit="onSubmitInvoices"
      @ok="handleModalSaveOk"
      @close="handleModalCancel"
    />
  </div>
</template>

<script>
import searchLayout from '@/views/app/biz/common/searchLayout'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import tableLayout from '@/views/app/biz/common/index'
import aListInfo from '@/views/app/biz/common/aListInfo'
import aListTable from '@/views/app/biz/common/aListTable'
import addModal from './addModal.vue'
import editDeliveryOrder from './editDeliveryOrder.vue'
// import viewModal from './viewModal'
import {
  getMergeOrder,
  saveMergeDetail,
  deleteMergeDetail,
  deleteMergeGoods
} from './saleDelivery'
import {
  deleteInfo
} from '../settlementInvoice/invoice.js'

const columns = [
  { title: '品名', dataIndex: 'productNameZh', key: 'productNameZh', align: 'center', },
  { title: '通用名', dataIndex: 'commonName', key: 'commonName', align: 'center' },
  { title: '生产企业名称', dataIndex: 'manufacturerZh', key: 'manufacturerZh', align: 'center', },
  { title: '规格', dataIndex: 'spec', key: 'spec', align: 'center' },
  { title: '型号', dataIndex: 'model', key: 'model', align: 'center' },
  { title: '计量单位', dataIndex: 'measurement', key: 'measurement', align: 'center' },
  // { title: '需配送数量', dataIndex: 'num', key: 'num', align: 'center' ,scopedSlots: { customRender: 'num' }},
  { title: '单价(元)', dataIndex: 'iunitprice', key: 'iunitprice', align: 'center', scopedSlots: { customRender: 'tofixed2' } },
  { title: '配送数量', dataIndex: 'num', key: 'num', align: 'center', scopedSlots: { customRender: 'num' } },
  { title: '总价(元)', dataIndex: 'totalPrice', key: 'totalPrice', align: 'center', scopedSlots: { customRender: 'totalPrices' } },
  { title: '操作', dataIndex: 'action', key: 'operation', width: 180, align: 'center', scopedSlots: { customRender: 'action' } },
]
let links = ['saleOrderNo',]
let autoComputed = ['num', 'totalPrices']

export default {
  components: {
    searchLayout,
    batchOperatBtn,
    tableLayout,
    aListInfo,
    aListTable,
    // viewSaleOrderModal,
    // viewModal, 
    addModal,
    editDeliveryOrder
  },
  props: {
    conditions: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    return {
      btn: [
        { name: '配送单信息', isUp: true },
        { name: '配送单明细', isUp: true },
        { name: '发票信息', isUp: true }
      ],
      columns: columns,
      listdata: [],
      links: links,
      autoComputed: autoComputed,
      loading: false,
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 100000, //每页显示条数 pageSize
        total: 1,
        // showQuickJumper: true,
        // showSizeChanger: true,
        // pageSizeOptions: ['2', '10', '50', '100'],
      },
      // 查询表单
      q_formInfos: [
      ],
      // 查询表单绑定数据
      q_formDatas: {
        pid: null
      },
      pData: {}, // 条件查询参数
      isJump: false,
      optText: '确认订单',
      selectedRowKeys: [],
      selectedRows: [],
      notAudit: false,

      innerTable: {
        innerColumns: [
          { title: '销售单号', dataIndex: 'saleOrderNo', key: 'saleOrderNo', align: 'center', },
          { title: '品名', dataIndex: 'productNameZh', key: 'productNameZh', align: 'center', },
          { title: '通用名', dataIndex: 'commonName', key: 'commonName', align: 'center' },
          // { title: '生产企业名称', dataIndex: 'manufacturerZh', key: 'manufacturerZh', align: 'center', },
          { title: '规格', dataIndex: 'spec', key: 'spec', align: 'center' },
          // { title: '型号', dataIndex: 'model', key: 'model', align: 'center' },
          { title: '计量单位', dataIndex: 'measurement', key: 'measurement', align: 'center' },
          // { title: '需配送数量', dataIndex: 'num', key: 'num', align: 'center' ,scopedSlots: { customRender: 'num' }},
          { title: '单价(元)', dataIndex: 'iunitprice', key: 'iunitprice', align: 'center', scopedSlots: { customRender: 'iunitprice' } },
          { title: '批号', dataIndex: 'batchCode', key: 'batchCode', align: 'center', width: '140px', scopedSlots: { customRender: 'batchCode' } },
          { title: '配送数量', dataIndex: 'num', key: 'num', align: 'center', width: '100px', scopedSlots: { customRender: 'num' } },
          { title: '生产日期', dataIndex: 'productDate', key: 'productDate', align: 'center', width: '140px', scopedSlots: { customRender: 'productDate' } },
          { title: '有效期', dataIndex: 'expiryDate', key: 'expiryDate', align: 'center', width: '140px', scopedSlots: { customRender: 'expiryDate' } },
          { title: '操作', dataIndex: 'action', key: 'operation', width: 150, align: 'center', scopedSlots: { customRender: 'action' } },
        ],
        innerInputName: [
          { name: 'num', type: 'number', placeholder: '数量' },
          { name: 'batchCode', type: 'text', placeholder: '批号' },
          { name: 'productDate', type: 'productDate', placeholder: '生产日期' },
          { name: 'expiryDate', type: 'expiryDate', placeholder: '有效期' },
        ],
        innerData: [],
        innerLoading: false,
      },
      columns2: [
        // { title: '结算单号', dataIndex: 'settlementNo', key: 'settlementNo', align: 'center' },
        { title: '买方单位', dataIndex: 'customerName', key: 'customerName', align: 'center' },
        // { title: '关联销售订单', dataIndex: 'saleOrderNo', key: 'saleOrderNo', align: 'center' },
        // { title: '买方税号', dataIndex: 'customerTaxNo', key: 'customerTaxNo', align: 'center' },
        // { title: '买方地址电话', dataIndex: 'customerAddrTell', key: 'customerAddrTell', align: 'center' },
        // { title: '买方银行账号', dataIndex: 'customerAccountNum', key: 'customerAccountNum', align: 'center' },
        // { title: '开具单位', dataIndex: 'supplierOrgName', key: 'supplierOrgName', align: 'center' },
        // { title: '开具单位税号', dataIndex: 'supplierTaxNo', key: 'supplierTaxNo', align: 'center' },
        // { title: '开具单位地址电话', dataIndex: 'supplierAddrTel', key: 'supplierAddrTel', align: 'center' },
        // { title: '开具单位银行账号', dataIndex: 'supplierAccountNum', key: 'supplierAccountNum', align: 'center' },
        { title: '发票种类', dataIndex: 'invoiceType', key: 'invoiceType', align: 'center' },
        { title: '发票号码', dataIndex: 'invoiceNo', key: 'invoiceNo', align: 'center' },
        { title: '发票代码', dataIndex: 'invoiceCode', key: 'invoiceCode', align: 'center' },
        // { title: '红票标志', dataIndex: 'redFlag', key: 'redFlag', align: 'center' },
        // { title: '无税总价', dataIndex: 'totalIunitprice', key: 'totalIunitprice', align: 'center',scopedSlots: { customRender: 'tofixed2' }  },
        { title: '含税总价', dataIndex: 'totalPrice', key: 'totalPrice', align: 'center', scopedSlots: { customRender: 'tofixed2' } },
        { title: '税率', dataIndex: 'tax', key: 'tax', align: 'center' },
        // { title: '税额', dataIndex: 'taxes', key: 'taxes', align: 'center' },
        { title: '状态', dataIndex: 'invoiceState', key: 'invoiceState', align: 'center' , scopedSlots: { customRender: 'percentage' }},
        { title: '操作', dataIndex: 'action', key: 'operation', width: 180, align: 'center', scopedSlots: { customRender: 'action' } },
      ],
      listdata2: [],
      pagination2: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 10, //每页显示条数 pageSize
        total: 1,
        // showQuickJumper: true,
        // showSizeChanger: true,
        // pageSizeOptions: ['2', '10', '50', '100'],
      },
      deliveryOrder: {},
      viewEdit: true
    }
  },
  computed: {},
  created () {
    
  },
  mounted () {
    console.log(this.$route.params);
    if (this.$route.params.pid) {
      this.q_formDatas.pid = this.$route.params.pid
      console.log('请求列表时传入的数据', this.q_formDatas)
      this.getList(this.q_formDatas)
    } else {
      this.onBack()
    }
  },
  methods: {
    onBack () {
      this.$router.push({
        name: 'deliverOrderyManage',
        params: {
          isJump: false,
          pathName: this.$route.name,
          iscloseMul: true,
        }
      })
    },
    onEdit (val) {
      this.viewEdit = val
      if (val) {
        this.$refs.deliveryOrder.onCancelEdit()
      } else {
        this.$refs.deliveryOrder.onEdit()
      }

    },
    onSave () {
      this.viewEdit = true
    },
    onSubmit () {
      this.$emit('onSubmit')
    },
    onCancel () {
      this.$emit('onCancel')
    },
    upAndDown (e, num) {
      if (this.btn[num].isUp) {
        this.btn[num].isUp = false
      } else {
        this.btn[num].isUp = true
      }
    },
    setPage () {
      const pagination = { ...this.pagination }
      if (this.listdata.length) {
        pagination.total = this.listdata.length
      }
      this.pagination = pagination
      this.pagination.showTotal = (showTotal) => { return `共 ${showTotal} 条` }
    },
    // 初始化查询时的数据列表
    async getList (params) {
      console.log('请求列表时传入的数据', params)
      let actionBtn = ['删除']
      this.loading = true
      this.listdata = []
      this.listdata2 = []
      let res = ''
      res = await getMergeOrder(params, this.pagination)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const deliveryOrderDetails = res.data.deliveryOrderDetails
        const invoices = res.data.invoices
        this.deliveryOrder = res.data.deliveryOrder
        for (let detailItem of deliveryOrderDetails) {
          for (const item of detailItem.child) {
            item.key = item.pid
            item.num = item.num ? item.num : null
            item.disabled = true
            item.batchCode = item.batchCode ? item.batchCode : null
            item.productDate = item.productDate ? item.productDate : null
            item.expiryDate = item.expiryDate ? item.expiryDate : null
            item.action = ['添加', '删除']
          }
          this.listdata.push({
            key: detailItem.pid,
            action: actionBtn,
            ...detailItem,

          })
        }
        for (let item of invoices) {
          this.listdata2.push({
            key: item.pid,
            action: actionBtn,
            ...item,

          })
        }
      } else {
        this.listdata = []
        this.listdata2 = []
      }
      this.setPage()
      console.log(this.listdata)
    },
    onAdd () {
      this.$refs.addModal.addModal(this.deliveryOrder.deliveryOrderNo)
    },
    onSubmitInvoices (val) {
      console.log(val);
    },
    // 关闭模态详细框
    handleModalCancel () {
    },
    // 模态详细框提交按钮
    handleModalSaveOk () {
      this.getList(this.q_formDatas)
    },
    // 操作按钮
    onAction (text, record, index) {
      if (text == '删除') {
        this.delItem(text, record, index)
      }
    },
    onInnerAction (text, record, index) {
      if (text == '删除') {
        this.delInnerItem(text, record, index)
      } else if (text == '添加') {
        this.addInnerItem(text, record, index)
      } else if (text == '移除') {
        this.removeInnerItem(text, record, index)
      }
    },
    onInnerBlur (text, record, index, col) {
      console.log(text, record, index, col);
      if (!record.batchCode) {
        this.$message.warning({ content: '商品批号不能为空', duration: 3 })
        return
      }
      if (!record.num) {
        this.$message.warning({ content: '配送数量不能为空', duration: 3 })
        return
      }
      if (!record.productDate) {
        this.$message.warning({ content: '生产日期不能为空', duration: 3 })
        return
      }
      if (!record.expiryDate) {
        this.$message.warning({ content: '有效期不能为空', duration: 3 })
        return
      }
      // delete record.action
      this.saveObjInfo(record)
    },
    async saveObjInfo (record) {
      let key = 'updatable'
      this.$message.loading({ content: '提交中', key, duration: 0 })
      console.log(record)
      let res = await saveMergeDetail(record)
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        this.$message.success({ content: '修改成功', key, duration: 3 })
        let parentItem = this.listdata.find(item => { return item.saleGoodsPid == record.saleGoodsPid })
        let parentItemIndex = this.listdata.findIndex(item => { return item.saleGoodsPid == record.saleGoodsPid })
        let changedIndex = parentItem.child.findIndex(item => { return item.key == record.key })
        res.data.action = ['添加', '删除']
        res.data.key = new Date().getTime()
        this.listdata[parentItemIndex].child.splice(changedIndex, 1, res.data)

      } else {
        this.$message.error({ content: '修改失败,请稍后再试', key, duration: 3 })
        this.getList(this.q_formDatas)
      }
    },
    addInnerItem (text, record, index) {
      console.log(record);
      let parentItem = this.listdata.find(item => { return item.saleGoodsPid == record.saleGoodsPid })
      let newRecord = JSON.parse(JSON.stringify(record))
      newRecord.action = ['移除']
      newRecord.pid = ''
      newRecord.sysSeq = 0
      newRecord.disabled = false
      newRecord.num = null
      newRecord.batchCode = null
      newRecord.productDate = null
      newRecord.expiryDate = null
      newRecord.key = new Date().getTime()
      let optInd = parentItem.child.findIndex(item => { return item.key == record.key })
      parentItem.child.splice(optInd + 1, 0, newRecord)
    },
    removeInnerItem (text, record, index) {
      console.log(record);
      let parentItem = this.listdata.find(item => {
        return item.saleGoodsPid == record.saleGoodsPid
      })
      parentItem.child.splice(index, 1)
    },
    delInnerItem (text, record, index) {
      let that = this
      this.$confirm({
        title: '是否确认删除？',
        content: '删除后不可恢复！',
        onOk () {
          console.log(record);
          that.deleteMergeDetail(record, index)
        },
        onCancel () { },
      });
    },
    async deleteMergeDetail (record, index) {
      let key = 'deleteMergeDetail'
      let res = await deleteMergeDetail(record)
      console.log(res);
      if (res && res.code && res.code === 'C1' && res.data) {
        this.$message.success({ content: '删除成功', key, duration: 3 })
        let parentItem = this.listdata.find(item => {
          return item.saleGoodsPid == record.saleGoodsPid
        })
        parentItem.child.splice(index, 1)
      } else {
        this.$message.error({ content: '删除失败,请稍后再试', key, duration: 3 })
        this.getList(this.q_formDatas)
      }
    },
    delItem (text, record, index) {
      let that = this
      this.$confirm({
        title: '是否确认删除？',
        content: '删除后不可恢复！',
        onOk () {
          console.log(record);
          that.deleteMergeGoods(record, index)
        },
        onCancel () { },
      });
    },
    async deleteMergeGoods (record, index) {
      let key = 'deleteMergeGoods'
      let res = await deleteMergeGoods(record)
      console.log(res);
      if (res && res.code && res.code === 'C1' && res.data) {
        this.$message.success({ content: '删除成功', key, duration: 3 })
        this.listdata.splice(index, 1)
      } else {
        this.$message.error({ content: '删除失败,请稍后再试', key, duration: 3 })
        this.getList(this.q_formDatas)
      }
    },
    // 触发改变页码,筛选,排序时的回调
    handleTableChange (pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
    },
    //点击展开表格
    onExpand (expanded, record) {
      console.log(expanded, record);
    },
    onChangeInput (aList) {

    },
    onTouchlinkCell (text, record, index, link) {
      console.log(record);
      if (link == 'saleOrderNo') {
        this.$refs.viewSaleOrderModal.showModal(record.pid, record)
      }
    },

    // 操作按钮
    onAction2 (text, record, index) {
      if (text == '删除') {
        let that = this
        this.$confirm({
          title: '是否确认删除？',
          content: '删除后不可恢复！',
          onOk () {
            console.log(record);
            that.deleteInfo(record, index)
          },
          onCancel () { },
        });

      }
    },
    async deleteInfo (val, index) {
      let key = 'deleteInfo'
      this.$message.loading({ content: '提交中', key })
      let res = await deleteInfo(val)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        this.$message.success({ content: '删除成功', key, duration: 2 })
        this.listdata2.splice(index, 1)
      } else {
        this.$message.success({ content: '删除失败', key, duration: 2 })
      }
    },
    // 多选批量操作
    onselectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      for (const item of this.selectedRows) {
        if (item.action[0] != '确认') {
          this.notAudit = true
          return
        } else {
          this.notAudit = false
        }
      }
    },

    onBatchAudit () {
      if (this.selectedRows.length) {
        if (this.notAudit) {
          this.$message.warning({ content: '已选项中含有已确认的记录，请选择未确认的记录', duration: 3 })
        } else {
          this.showConfirm(this.selectedRows)
        }
      } else {
        this.$message.warning({ content: '未选择要审核的记录', duration: 3 })
      }
    },

  },
}
</script>

<style>
.viewTitle {
  line-height: 30px;
  font-size: 16px;
  font-weight: bolder;
  color: #555;
  border-bottom: 1px solid #ccc;
  margin: 10px 0;
}
.upAndDown {
  text-align: center;
}
.card {
  width: 100%;
  padding: 0 7px;
}
.dis {
  height: 15px;
  background-color: #f0f2f5;
}
</style>